"""
文件工具
"""
import os
import shutil
from typing import List, Dict, Any
from pathlib import Path


def ensure_directory(path: str) -> bool:
    """确保目录存在"""
    try:
        os.makedirs(path, exist_ok=True)
        return True
    except Exception as e:
        print(f"创建目录失败: {e}")
        return False


def get_file_info(file_path: str) -> Dict[str, Any]:
    """获取文件信息"""
    if not os.path.exists(file_path):
        return {}
    
    path = Path(file_path)
    stat = path.stat()
    
    return {
        "file_path": str(path),
        "file_name": path.name,
        "file_extension": path.suffix.lower(),
        "file_size": stat.st_size,
        "created_time": stat.st_ctime,
        "modified_time": stat.st_mtime,
        "is_file": path.is_file(),
        "is_directory": path.is_directory(),
    }


def list_files(
    directory: str, 
    extensions: List[str] = None,
    recursive: bool = False
) -> List[str]:
    """列出目录中的文件"""
    if not os.path.exists(directory):
        return []
    
    files = []
    path = Path(directory)
    
    if recursive:
        pattern = "**/*"
    else:
        pattern = "*"
    
    for file_path in path.glob(pattern):
        if file_path.is_file():
            if extensions is None or file_path.suffix.lower() in extensions:
                files.append(str(file_path))
    
    return files


def copy_file(src: str, dst: str, overwrite: bool = False) -> bool:
    """复制文件"""
    try:
        if os.path.exists(dst) and not overwrite:
            return False
        
        # 确保目标目录存在
        dst_dir = os.path.dirname(dst)
        ensure_directory(dst_dir)
        
        shutil.copy2(src, dst)
        return True
    except Exception as e:
        print(f"复制文件失败: {e}")
        return False


def move_file(src: str, dst: str, overwrite: bool = False) -> bool:
    """移动文件"""
    try:
        if os.path.exists(dst) and not overwrite:
            return False
        
        # 确保目标目录存在
        dst_dir = os.path.dirname(dst)
        ensure_directory(dst_dir)
        
        shutil.move(src, dst)
        return True
    except Exception as e:
        print(f"移动文件失败: {e}")
        return False


def delete_file(file_path: str) -> bool:
    """删除文件"""
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
        return False
    except Exception as e:
        print(f"删除文件失败: {e}")
        return False


def get_file_size(file_path: str) -> int:
    """获取文件大小"""
    try:
        return os.path.getsize(file_path)
    except:
        return 0


def is_valid_file(file_path: str, max_size: int = None) -> bool:
    """检查文件是否有效"""
    if not os.path.exists(file_path):
        return False
    
    if not os.path.isfile(file_path):
        return False
    
    if max_size is not None:
        file_size = get_file_size(file_path)
        if file_size > max_size:
            return False
    
    return True


def get_relative_path(file_path: str, base_path: str) -> str:
    """获取相对路径"""
    try:
        file_path = Path(file_path).resolve()
        base_path = Path(base_path).resolve()
        return str(file_path.relative_to(base_path))
    except:
        return file_path 